package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.http.HttpClient;
import java.time.LocalDateTime;
import java.util.HashMap;

@Service
public class UserServiceImpl implements UserService {
    //微信开发者接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatProperties weChatProperties;
    @Override
    public UserLoginVO wxLogin(UserLoginDTO userLoginDTO) {

        //调用微信接口服务获取微信唯一的openid,使用httpclient请求获取openid
        HashMap<String, String> CodeMap = new HashMap<String, String>();
        CodeMap.put("appid",weChatProperties.getAppid());
        CodeMap.put("secret",weChatProperties.getSecret());
        CodeMap.put("js_code",userLoginDTO.getCode());
        CodeMap.put("grant_type","authorization_code");
        //发送请求.返回一个json字符串
        String s = HttpClientUtil.doGet(WX_LOGIN, CodeMap);
        //将json字符串转换为json对象
        JSONObject jsonObject = JSON.parseObject(s);
        //获取openid
        String openid = jsonObject.getString("openid");

        //判断返回的openid是否为空
        if(openid == null){
            //如果为空，说明登录失败，抛出异常
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //根据openid查询数据库是否存在用户，如果不存在则自动完成注册到自己的数据库
        User user = userMapper.getByOpenid(openid);
        if (user == null){
            //如果不存在，自动完成注册
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }
        //如果存在，登录成功，将user对象转换为UserLoginVO对象
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .build();

        return userLoginVO;
    }
}
